package com.training.admin.web.controller.report;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.report.TrainerReport;
import com.training.admin.entity.search.TrainerReportSearch;
import com.training.admin.entity.trainer.Trainer;
import com.training.admin.service.ProjectPhaseCourseService;
import com.training.admin.service.ReportService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.web.controller.view.ExcelTemplateView;

/**
 * 报表
 * 
 * @author Rockett
 * 
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-report")
public class TrainerReportController {

	@Autowired
	private ReportService reportService;
	
	@Autowired
	private TrainingSurveyResultService trainingSurveyResultService;
	
	@Autowired
	private ProjectPhaseCourseService projectPhaseCourseService;

	/**
	 * 内部讲师表
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/trainer-report", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-report")
	public ModelAndView trainerReportSearch(Page page) {
		ModelAndView modelAndView = new ModelAndView("report/trainer-report-search");

		return modelAndView;
	}

	/**
	 * 内部讲师表
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/trainer-report", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-trainer-report")
	@SuppressWarnings("rawtypes")
	public ModelAndView onTrainerReportSearch(TrainerReportSearch trainerReportSearch, Page page,
			HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("report/trainer-report");

		// 不做事业部过滤
//		Login login = (Login)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		Principal principal = principalService.loadByEmail(login.getEmail());
//		if(principal.getAuthority().equals("ROLE_SUPER_USER")){
//			//系统管理员
//			//do nothing
//		}else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")){
//			//事业部负责人
//			trainerReportSearch.setDepartmentId(principal.getDepartmentId());
//		}

		int totals = reportService.count(trainerReportSearch);
		if (totals > 0) {

			List trainerList = reportService.search(trainerReportSearch, page.with(totals));
			List<TrainerReport> trainerReportList = new ArrayList<TrainerReport>();
			for (int i = 0; i < trainerList.size(); i++) {
				Trainer trainer = (Trainer) trainerList.get(i);
				TrainerReport trainerReport = new TrainerReport(trainer);
				// 调查结果平均分
				Double avgScore = trainingSurveyResultService.avgByTrainer(trainer.getId());
				if(avgScore != null) {
				    BigDecimal bd = new BigDecimal(avgScore);
	                double d1 =bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	                trainerReport.setSatisfaction(avgScore == null ? "" : String.valueOf(d1));
				} else {
	                trainerReport.setSatisfaction(null);
				}
				
				
//				List <TrainingSurveyResult>  trainingSurveyResults = trainingSurveyResultService.listScoreByTrainer(trainer.getId());
//				int total=0;
//				int cnt=0;
//				if(trainingSurveyResults!=null && trainingSurveyResults.size()>0){
//					
//					for (int j=0;j<trainingSurveyResults.size();j++){
//						TrainingSurveyResult tsr = trainingSurveyResults.get(j);
//						String inputVal = tsr.getInputValue();
//						//check category
//						if(tsr.getCategory()!=null && tsr.getCategory().contains("专业通识")){
//							//专业通识类, 不检查keywords 只判断是否int型
//							try{
//							    if(tsr.getProjectPhaseCourse() != null) {
//							        int intVal=Integer.parseInt(inputVal);
//	                                if(total>5){
//	                                    //非正常值
//	                                    continue;
//	                                }
//	                                total+=intVal;
//	                                cnt++;
//							    }
//							}catch(Exception e){
//							    logger.error(e.getMessage());
//							}
//						}else{
//							//check keywords
//							if(tsr.getKeywords()!=null && tsr.getKeywords().length()>0){
//								if(tsr.getKeywords().contains("讲师")){
//									try{
//										int intVal=Integer.parseInt(inputVal);
//										if(total>5){
//											//非正常值
//											continue;
//										}
//										total+=intVal;
//										cnt++;
//									}catch(Exception e){
//										logger.error(e.getMessage());
//									}
//								}
//							}else{
//								//no keywords, check question body
//								if(tsr.getQuestion().contains("讲师")){
//									try{
//										total+=Integer.parseInt(inputVal);
//										cnt++;
//									}catch(Exception e){
//										logger.error(e.getMessage());
//									}
//								}
//								
//							}
//						
//						}
//					}
//					
//				}
//				
//				
//				
//				if(total==0|| cnt==0){
//					trainerReport.setSatisfaction("");
//				}else{
//				    BigDecimal bd=new BigDecimal(total*1.0/cnt);
//		            double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//					trainerReport.setSatisfaction(""+ String.valueOf(d1));
//				}
				// 统计授课总时长， 课程集合
				List<ProjectPhaseCourse> courseList = projectPhaseCourseService.listByTrainer(trainer.getId());
				int trainingHour = 0;
				String courseString = "";
				List<String> courseNames=new ArrayList<String>();
				if (courseList != null && courseList.size() > 0) {
					for (int j = 0; j < courseList.size(); j++) {
						ProjectPhaseCourse course = courseList.get(j);
						trainingHour += course.getCourse().getHour();
						if(!courseNames.contains(course.getCourse().getName())){
							courseNames.add(course.getCourse().getName());
						}
						//courseString += "," + course.getCourse().getName();
					}
				}
				for(int idx=0;idx<courseNames.size();idx++){
					courseString += "," + courseNames.get(idx);
				}
				if (courseString.length() > 0) {
					courseString = courseString.substring(1);
				}
				trainerReport.setTrainingHour(trainingHour);
				trainerReport.setCourses(courseString);
				trainerReportList.add(trainerReport);
			}

			modelAndView.addObject("trainerReportList", trainerReportList);
			modelAndView.addObject("recordCount", trainerReportList.size());
			modelAndView.addObject("page", page);

		}

		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		return modelAndView;
	}

	/**
	 * 内部讲师表 - 导出
	 * 
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/reports/trainer-report-export", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-report")
	@SuppressWarnings("rawtypes")
	public ModelAndView trainerReportExport(TrainerReportSearch trainerReportSearch, Page page) {

		ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("trainer-report.xls", "trainer-eport.xls"));
		// 不做事业部过滤
//		Login login = (Login)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		Principal principal = principalService.loadByEmail(login.getEmail());
//		if(principal.getAuthority().equals("ROLE_SUPER_USER")){
//			//系统管理员
//			//do nothing
//		}else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")){
//			//事业部负责人
//			trainerReportSearch.setDepartmentId(principal.getDepartmentId());
//		}

		int totals = reportService.count(trainerReportSearch);
		if (totals > 0) {
				List trainerList = reportService.search(trainerReportSearch, page.with(totals));
				List<TrainerReport> trainerReportList = new ArrayList<TrainerReport>();
				for (int i = 0; i < trainerList.size(); i++) {
					Trainer trainer = (Trainer) trainerList.get(i);
					TrainerReport trainerReport = new TrainerReport(trainer);
					// 调查结果平均分
					Double avgScore = trainingSurveyResultService.avgByTrainer(trainer.getId());
	                if(avgScore != null) {
	                    BigDecimal bd = new BigDecimal(avgScore);
	                    double d1 =bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	                    trainerReport.setSatisfaction(avgScore == null ? "" : String.valueOf(d1));
	                } else {
	                    trainerReport.setSatisfaction(null);
	                }
					
//					List <TrainingSurveyResult>  trainingSurveyResults = trainingSurveyResultService.listScoreByTrainer(trainer.getId());
//					int total=0;
//					int cnt=0;
//					if(trainingSurveyResults!=null && trainingSurveyResults.size()>0){
//						
//						for (int j=0;j<trainingSurveyResults.size();j++){
//							TrainingSurveyResult tsr = trainingSurveyResults.get(j);
//							String inputVal = tsr.getInputValue();
//							//check category
//							if(tsr.getCategory()!=null && tsr.getCategory().contains("专业通识")){
//								//专业通识类, 不检查keywords 只判断是否int型
//								try{
//									int intVal=Integer.parseInt(inputVal);
//									if(total>5){
//										//非正常值
//										continue;
//									}
//									total+=intVal;
//									cnt++;
//								}catch(Exception e){
//									logger.error(e.getMessage());
//								}
//							}else{
//								//check keywords
//								if(tsr.getKeywords()!=null && tsr.getKeywords().length()>0){
//									if(tsr.getKeywords().contains("讲师")){
//										try{
//											int intVal=Integer.parseInt(inputVal);
//											if(total>5){
//												//非正常值
//												continue;
//											}
//											total+=intVal;
//											cnt++;
//										}catch(Exception e){
//											logger.error(e.getMessage());
//										}
//									}
//								}else{
//									//no keywords, check question body
//									if(tsr.getQuestion().contains("讲师")){
//										try{
//											total+=Integer.parseInt(inputVal);
//											cnt++;
//										}catch(Exception e){
//											logger.error(e.getMessage());
//										}
//									}
//									
//								}
//							
//							}
//						}
//						
//					}
//					
//					if(total==0|| cnt==0){
//						trainerReport.setSatisfaction("");
//					}else{
//						trainerReport.setSatisfaction(""+ total*1.0/cnt);
//					}
					// 统计授课总时长， 课程集合
					List<ProjectPhaseCourse> courseList = projectPhaseCourseService.listByTrainer(trainer.getId());
					int trainingHour = 0;
					String courseString = "";
					List<String> courseNames=new ArrayList<String>();
					if (courseList != null && courseList.size() > 0) {
						for (int j = 0; j < courseList.size(); j++) {
							ProjectPhaseCourse course = courseList.get(j);
							trainingHour += course.getCourse().getHour();
							if(!courseNames.contains(course.getCourse().getName())){
								courseNames.add(course.getCourse().getName());
							}
							//courseString += "," + course.getCourse().getName();
						}
					}
					for(int idx=0;idx<courseNames.size();idx++){
						courseString += "," + courseNames.get(idx);
					}
					if (courseString.length() > 0) {
						courseString = courseString.substring(1);
					}
					trainerReport.setTrainingHour(trainingHour);
					trainerReport.setCourses(courseString);
					trainerReportList.add(trainerReport);
				}


			modelAndView.addObject("results", trainerReportList);

		}

		return modelAndView;

	}

}
